package com.starinside.wp.handler;

import com.starinside.wp.domain.WxUser;
import com.starinside.wp.repository.WxUserRepository;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class UnsubscribeHandler extends AbstractHandler {

    @Autowired
    WxUserRepository wxUserRepository;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser();
        this.logger.info("取消关注用户 OPENID: " + openId);

        // TODO 可以更新本地数据库为取消关注状态
        Optional<WxUser> uo = wxUserRepository.findByOpenidWp(openId);
        if(uo.isPresent()){
            WxUser wxUser = uo.get();

            wxUser.setSubscribe(false);

            wxUserRepository.saveAndFlush(wxUser);
        }

        return null;
    }

}
